import {
  deleteUserById,
  newUserData,
  postUsersListData,
  editUserData,
  postPageListData,
  deletePageById,
  newPageData,
  editPageData
} from '@/service/main/system/system'
import { defineStore } from 'pinia'
import type { ISystemState } from './type'
import useMainStore from '../main'

const useSystemStore = defineStore('system', {
  state: (): ISystemState => ({
    usersList: [],
    usersTotalCount: 0,
    pageList: [],
    pageTotalCount: 0
  }),
  actions: {
    async postUsersListAction(reqInfo: any) {
      const usersListResult = await postUsersListData(reqInfo)
      // console.log(usersListResult.data)
      const { totalCount, list } = usersListResult.data
      this.usersTotalCount = totalCount
      this.usersList = list

      // 获取完整的数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    },
    async deleteUserByIdAction(id: number) {
      const deleteResult = await deleteUserById(id)
      // console.log(deleteResult)

      this.postUsersListAction({ offset: 0, size: 10 })

      return new Promise((resolve, reject) => {
        resolve(deleteResult.code)
        reject('error')
      })
    },
    // 创建新的用户
    async newUserDataAction(userInfo: any) {
      const newResult = await newUserData(userInfo)
      // console.log(newResult)
      // 重新请求数据
      this.postUsersListAction({ offset: 0, size: 10 })
    },
    // 更新用户数据
    async editUserDataAction(id: number, itemData: any) {
      const editResult = await editUserData(id, itemData)
      // console.log(editResult)
      // 重新请求数据
      this.postUsersListAction({ offset: 0, size: 10 })
    },

    // 针对页面的数据，增删改查
    async postPageListAction(pageName: string, queryInfo: any) {
      const pageListResult = await postPageListData(pageName, queryInfo)
      const { totalCount, list } = pageListResult.data
      this.pageTotalCount = totalCount
      this.pageList = list

      // 获取完整的数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()
    },
    async deletePageByIdAction(pageName: string, id: number) {
      const deleteResult = await deletePageById(pageName, id)
      // console.log(deleteResult)
      this.postPageListAction(pageName, { offset: 0, size: 10 })
      return new Promise((resolve, reject) => {
        resolve(deleteResult.code)
        reject('error')
      })
    },
    async newPageDataAction(pageName: string, pageInfo: any) {
      const newResult = await newPageData(pageName, pageInfo)
      // console.log(newResult)
      // 重新请求数据
      this.postPageListAction(pageName, { offset: 0, size: 10 })
    },
    async editPageDataAction(pageName: string, id: number, itemData: any) {
      const editResult = await editPageData(pageName, id, itemData)
      // console.log(editResult)
      // 重新请求数据
      this.postPageListAction(pageName, { offset: 0, size: 10 })
    }
  }
})

export default useSystemStore
